package com.smarth.zhizulian.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.google.gson.reflect.TypeToken;
import com.smarth.zhizulian.R;
import com.smarth.zhizulian.activity.AgentWebActivity;
import com.smarth.zhizulian.activity.GetMoneyActivity;
import com.smarth.zhizulian.activity.GetMoneyCenterActivity;
import com.smarth.zhizulian.activity.LoginActivity;
import com.smarth.zhizulian.activity.SearchActivity;
import com.smarth.zhizulian.adapter.MyPagerAdapter;
import com.smarth.zhizulian.app.BaseConfig;
import com.smarth.zhizulian.app.EventFragment;
import com.smarth.zhizulian.bean.Category;
import com.smarth.zhizulian.entity.EventBean;
import com.smarth.zhizulian.http.KumaHttp;
import com.smarth.zhizulian.http.observer.inter.BaseObserver;
import com.smarth.zhizulian.http.utils.RxCompos;
import com.smarth.zhizulian.popupwindow.PWCategory;
import com.smarth.zhizulian.utils.ACache;
import com.smarth.zhizulian.utils.GsonUtils;
import com.smarth.zhizulian.utils.UserUtils;
import com.smarth.zhizulian.utils.listhelper.RefreshHelper;
import com.smarth.zhizulian.utils.listhelper.impl.adapter.PageDataAdapter;
import com.smarth.zhizulian.utils.listhelper.impl.model.PageDataModel;
import com.smarth.zhizulian.utils.listhelper.inter.ResponseSender;
import com.smarth.zhizulian.view.LoadingLayout;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
import com.umeng.analytics.MobclickAgent;

import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by 18865 on 2017/12/20.
 */

public class IndexFragment extends EventFragment {
    @BindView(R.id.tl_tablayout)
    SmartTabLayout tlTablayout;
    @BindView(R.id.vp_viewpager)
    ViewPager vpViewpager;
    MyPagerAdapter pagerAdapter;
    @BindView(R.id.iv_open)
    ImageView ivOpen;
    @BindView(R.id.rl_tab)
    RelativeLayout rlTab;
    @BindView(R.id.v_titlebar)
    View vTitlebar;
    @BindView(R.id.ll_all)
    LinearLayout llAll;
    @BindView(R.id.ll_loadinglayout)
    LoadingLayout llLoadinglayout;
    @BindView(R.id.rl_hongbao)
    RelativeLayout rlHongbao;
    private List<Category> mCategories = new ArrayList<>();
    public static final String BUNDLE_MODE = "BUNDLE_MODE";
    public static final int MODE_NORMAL = 0;
    public static final int MODE_HIGH = 1;      //跳转高价文

    private RefreshHelper<List<Category>> refreshHelper;

    @Override
    protected void onCreateView(Bundle savedInstanceState) {
        super.onCreateView(savedInstanceState);
        setBKView(R.layout.fragment_index);
        initTab();
    }

    @Override
    protected void onLogin(EventBean eb) {

    }

    private void initTab() {
        refreshHelper = new RefreshHelper(mContext, llLoadinglayout, null);
        refreshHelper.setDataModel(new PageDataModel<List<Category>>() {
            @Override
            public void fetch(final ResponseSender<List<Category>> responseSender) {
                KumaHttp.getService().articleArticleTypes()
                        .compose(RxCompos.<List<Category>>getBECompos())
                        .doOnSubscribe(new Consumer<Disposable>() {
                            @Override
                            public void accept(Disposable disposable) throws Exception {
                                try {
                                    String categoriesJson = ACache.get(mContext).getAsString(BaseConfig.ACache.CATEGORIES);
                                    List<Category> categories = GsonUtils.fromJson(categoriesJson, new TypeToken<List<Category>>() {
                                    });
                                    if (categories != null && categories.size() != 0) {
//                                        createTab(categories);
                                        refreshHelper.sendData(categories);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        })
                        .subscribe(new BaseObserver<List<Category>>(mContext) {
                            @Override
                            public void onNext(List<Category> categories) {
                                responseSender.sendData(categories);
                            }

                            @Override
                            public void onError(Throwable e) {
                                super.onError(e);
                                if (mCategories == null || mCategories.size() == 0) {
                                    responseSender.sendError((Exception) e);
                                }
                            }
                        });
            }
        });
        refreshHelper.setDataAdapter(new PageDataAdapter<List<Category>>() {
            @Override
            public void onGetData(List<Category> categories, boolean isRefresh) {
                super.onGetData(categories, isRefresh);
                createTab(categories);
                String cacheJson = GsonUtils.toJson(categories);
                ACache.get(mContext).put(BaseConfig.ACache.CATEGORIES, cacheJson);
            }

            @Override
            public boolean isDataEmpty() {
                return mCategories == null || mCategories.size() == 0;
            }
        });
        refreshHelper.refresh();
    }


    @OnClick({R.id.iv_open, R.id.iv_standard, R.id.iv_close, R.id.iv_hongbao, R.id.ll_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_open:
                PWCategory pw = new PWCategory(mContext, mCategories, mCategories.get(vpViewpager.getCurrentItem()));
                pw.setOnResultListener(new PWCategory.OnResultListener() {
                    @Override
                    public void onResult(Category category) {
                        for (int i = 0; i < mCategories.size(); i++) {
                            if (mCategories.get(i).getId() == category.getId()) {
                                vpViewpager.setCurrentItem(i);
                            }
                        }
                    }
                });
                pw.showAsDropDown(vTitlebar);
                break;
            case R.id.iv_standard:
                AgentWebActivity.openForStandard(mContext);
                break;
            case R.id.iv_close:
                rlHongbao.setVisibility(View.GONE);
                break;
            case R.id.iv_hongbao:
                if (UserUtils.isLogin()) {
                    GetMoneyCenterActivity.open(mContext);
                } else {
                    LoginActivity.open(mContext);
                }
                break;
            case R.id.ll_search:
                SearchActivity.open(mContext, SearchActivity.MODE_NEWS);
                break;
        }
    }

    private void createTab(List<Category> categories) {
        mCategories = categories;
        List<Fragment> fragmentList = new ArrayList<>();
        List<String> titleList = new ArrayList<>();
        for (int i = 0; i < categories.size(); i++) {
            fragmentList.add(CategoryFragment.getInstance(categories.get(i)));
            titleList.add(categories.get(i).getName());
        }
        pagerAdapter = new MyPagerAdapter(mContext, getChildFragmentManager(), fragmentList, titleList);
        vpViewpager.setAdapter(pagerAdapter);
        vpViewpager.setOffscreenPageLimit(2);
        tlTablayout.setViewPager(vpViewpager);
        rlTab.setVisibility(View.VISIBLE);
    }

    @Subscriber(tag = "IndexFragment")
    private void showHigh(EventBean eb) {
        switch (eb.getCode()) {
            case BaseConfig.EventCode.SHOW_HIGH:
                if (mCategories != null && mCategories.size() > 0) {
                    int index = -1;
                    for (int i = 0; i < mCategories.size(); i++) {
                        if (mCategories.get(i).getId() == 2) {
                            index = i;
                            break;
                        }
                    }
                    if (index != -1) {
                        vpViewpager.setCurrentItem(index);
                    }
                }
                break;
            case BaseConfig.EventCode.SHOW_FIRST:
                if (mCategories != null && mCategories.size() > 0) {
                    vpViewpager.setCurrentItem(0);
                }
                break;
        }
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("IndexFragment");
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("IndexFragment");
    }
}
